import React, { useEffect, useState,useMemo } from "react";
import { getFormatDate,highlightText } from "@/utils";
import { Tooltip, Input, Modal,Empty, Spin } from "antd";
import { SearchOutlined,EditOutlined,DeleteOutlined,ExclamationCircleFilled,LoadingOutlined } from "@ant-design/icons";
import { useChatStore,useUserStore } from "@/store";
import { motion, AnimatePresence } from "framer-motion";
import { containerVariants, itemVariants } from "./animate";
import { Avatar } from 'antd';
interface ChatListProps {
  onClickConversation: (conversationId:number) => void
}

export default React.FC<ChatListProps> = (props: ChatListProps) => {
  const { onClickConversation } = props
  const {
    chatHistoryList,
    currentConversation,
    clearMessageListAction,
    getAllChatHistoryAction,
    deleteConversationAction,
    getConversationListFetchAction,
    updateCurrentConversationAction,
  } = useChatStore(state => state);
  const { userInfo } = useUserStore(state => state);
  const [chatHistoryObject, setChatHistoryObject] = useState<any>({});

  const [chatKeyword, setChatKeyword] = useState<string>('');

  const { confirm } = Modal;

  useEffect(() => {
    const arr = formatChatHistoryObject(chatHistoryList);
    setChatHistoryObject(arr);
  }, [chatHistoryList]);

  // 实现文本筛选并且高亮
  useEffect(() => {
    const filteredList = chatHistoryList.filter(chat => 
      chat.title.toLowerCase().includes(chatKeyword.toLowerCase())
    ).map(chat => ({
      ...chat,
      title: highlightText(chat.title, chatKeyword)
    }));
    const newChatHistoryObject = formatChatHistoryObject(filteredList);
    setChatHistoryObject(newChatHistoryObject);
  }, [chatKeyword, chatHistoryList]);

  const formatChatHistoryObject = (data) => {
    const arr = data.reduce((acc, cur) => {
      const date = getFormatDate(new Date(cur.createdAt));
      if (!acc[date]) {
        acc[date] = [];
      }
      acc[date].push(cur);
      return acc;
    }, {});
    return arr;
  };

  const deleteConversation = (chat:any,e:React.MouseEvent) => {
    e.stopPropagation();
    console.log(chat)
    confirm({
      title: `确定删除该对话吗？`,
      icon: <ExclamationCircleFilled />,
      centered: true,
      cancelText: '取消',
      okText: '确定',
      content: '确定删除之后无法恢复，是否确认删除？',
      onOk() {
        return new Promise((resolve, reject) => {
          deleteConversationAction({conversationId:chat.id}).then(res => {
            resolve(res)
            getConversationListFetchAction().then((newChatHistoryList:any) => {
              const conversation = newChatHistoryList[0] || {}
              clearMessageListAction()
              updateCurrentConversationAction(conversation)
              getAllChatHistoryAction(conversation)
            })
          }).catch(err => {
            reject(err)
          })
        }).catch((e) => {
          console.log('Oops errors!',e)
        });
      },
      onCancel() {},
    });
  }
  return (
    <>
      <div className="c_aside_search">
        <Input placeholder="搜索对话" variant="borderless" size="large" value={chatKeyword} onChange={(e) => setChatKeyword(e.target.value)}/>
        <SearchOutlined
          style={{ fontSize: "16px", color: "#1677ff", cursor: "pointer" }}
        />
      </div>
      <div className="c_chat_list_wrapper">
        {chatHistoryList.length > 0 ? Object.keys(chatHistoryObject).map((item,index) => {
          return (
            <div className="c_chat_list_history_wrapper" key={item}>
              <h3 className="c_chat_list_history_title">{item}</h3>
              <motion.ul 
                className="c_chat_list_history_list"
                variants={containerVariants}
                initial="hidden"
                animate="visible"
              >
                  <AnimatePresence mode="popLayout">
                    {chatHistoryObject[item].map((chat: any) => (
                      <motion.div
                        key={chat.id}
                        variants={itemVariants}
                        layout
                        custom={index}
                      >
                        <Spin wrapperClassName="c_custom_conversation_spin" indicator={<LoadingOutlined spin />} size="small" spinning={chat.loading}>
                          <Tooltip placement="topLeft" title={<div dangerouslySetInnerHTML={{ __html: chat.title }} />}>
                            <li 
                              className={`c_chat_list_history_item ${currentConversation.id === chat.id ? 'c_chat_list_history_item_active' : ''}`} 
                              onClick={() => onClickConversation(chat)}
                              >
                                <span dangerouslySetInnerHTML={{ __html: chat.title }}></span>
                                <div className="c_chat_list_history_item_option">
                                  <EditOutlined style={{ fontSize: '16px', marginRight: '8px'}}/>
                                  <DeleteOutlined style={{fontSize: '16px'}} onClick={(e) => deleteConversation(chat,e)}/>
                                </div>
                              </li>
                            </Tooltip>
                          </Spin>
                      </motion.div>
                    ))}
                  </AnimatePresence>
              </motion.ul>
            </div>
          );
        }) : <div className="c_chat_list_history_empty">
          <Empty description="暂无对话"/>
        </div>}
      </div>
      {
        userInfo ? <div className="c_user_info_box">
        <Avatar shape="square" src={userInfo.avatar} size={32}/>
        <span>{userInfo.userName}</span>
        </div> : ''
      }

    </>
  );
};
